import {
  ADD_CAR_ITEM,
  CarAction,
  ADD_CAR_ITEM_COUNT,
  SUB_CAR_ITEM_COUNT,
  SWITCH_CAR_ITEM,
  MODIFY_ALL_CAR_ITEM_ISChECKED,
  DELETE_CAR_ITEMS,
  ADD_CAR_ITEM_CUSTOM_COUNT,
} from "./carAction";

export interface CarState {
  car: CarItem[];
}

export interface CarItem {
  title: string;
  desc: string;
  url: string;
  id: string;
  price: number;
  count: number;
  isChecked: boolean;
}

const initState: CarState = {
  car: JSON.parse(localStorage.getItem("car") || "[]"),
};

export default (state = initState, action: CarAction) => {
  switch (action.type) {
    case ADD_CAR_ITEM: {
      const item = state.car.find((v) => v.id === action.payload.id);
      if (item) {
        // 存在
        item.count++;
      } else {
        // 不存在
        state.car.push({ ...action.payload, count: 1, isChecked: false });
      }

      return {
        ...state,
        car: [...state.car],
      };
    }
    case ADD_CAR_ITEM_COUNT: {
      const item = state.car.find((v) => v.id === action.payload);
      item && item.count++;
      return {
        ...state,
        car: [...state.car],
      };
    }
    case SUB_CAR_ITEM_COUNT: {
      const item = state.car.find((v) => v.id === action.payload);
      item && item.count--;
      return {
        ...state,
        car: [...state.car],
      };
    }
    case SWITCH_CAR_ITEM: {
      const item = state.car.find((v) => v.id === action.payload);
      if (item) item.isChecked = !item.isChecked;
      return {
        ...state,
        car: [...state.car],
      };
    }
    case MODIFY_ALL_CAR_ITEM_ISChECKED: {
      state.car.forEach((v) => (v.isChecked = action.payload));
      return {
        ...state,
        car: [...state.car],
      };
    }
    case DELETE_CAR_ITEMS: {
      return {
        ...state,
        car: state.car.filter((v) => !v.isChecked),
      };
    }
    case ADD_CAR_ITEM_CUSTOM_COUNT: {
      const item = state.car.find((v) => v.id === action.payload.item.id);

      if (item) {
        item.count += action.payload.count;
      } else {
        state.car.push({
          ...action.payload.item,
          count: action.payload.count,
          isChecked: false,
        });
      }

      return {
        ...state,
        car: [...state.car]
      }
    }
    default: {
      return state;
    }
  }
};
